<?php
/*
	后台导航数据模型
*/	
class sidebar_model extends Base_Model{
	
	private $menu=array();	//导航数组
	
	/*
	 * 生成格式化的导航数组
	 * @param $parent_id 父级导航id
	 * @return array
	*/
	public function get_all_menu( $parent_id = 0 ){
		
		$menu = $this->db->order_by( 'order' )->get_where( 'menu', array( 'parent_id'=>$parent_id ) )->result_array();
		if( ! empty( $menu ) ){
			foreach( $menu as $k=>$v ){
				$menu[$k]['sub'] = $this->get_all_menu( $v['id'] );
			}
		}		
		return $menu;
	}
	
	/**
	 * 从数据库获取导航数组（分级）
	 * @param $parent_id 父级导航id
	 * @return array
     */
	public function get_role_menu( $parent_id = 0 ){
		 
		//获取当前用户的用户组权限
		$this->load->model( 'user_model' );
		$user = $this->user_model->get_user_by_id( sess( 'id' ) );
		$group = $this->user_model->get_group_by_id( $user->group );
		$permit = explode( ',', $group['permit'] );
		//查询有权限访问的菜单
		$menu = $this->db->order_by( 'order' )->where_in( 'id', $permit )->where( 'parent_id', $parent_id )->get( 'menu' )->result_array();
		if( ! empty( $menu ) ){
			foreach( $menu as $k=>$v ){
				$menu[$k]['sub'] = $this->get_role_menu( $v['id'] );
			}
		}		
		return $menu;

	}
	
	/*
	 * 获取某一层级的菜单
	 * @param int 父级菜单id
	 * 	@return obj
	*/
	public function get_menus_by_parent_id( $parent_id = 0 ){

		return $this->db->order_by( 'order' )->get_where('menu', array( 'parent_id'=>(int)$parent_id ) )->result();
	}

	/*
	 * 获取某一id的菜单数据
	 * @param int 菜单id
	 * 	@return obj
	*/
	public function get_menu_by_id( $id = 0 ){

		return $this->db->get_where( 'menu', array( 'id'=>(int)$id ) )->row();
	}
	/*
	 * 获取某一URL的菜单数据
	 * @param string 菜单url
	 * @return array
	*/
	public function get_menu_by_url( $url ){

		return $this->db->get_where( 'menu', array( 'url'=>$url ) )->row_array();
	}
		
	/* 增加菜单
	 * @param array 菜单数据
	 * @return bool
	 * */
	public function add_menu( $arr ){
		
		return $this->db->insert( 'menu', $arr );
	} 
	/*
	 * 修改菜单
	 * @param array 菜单信息
	 * @return bool
     */
	public function update_menu( $data ){	 

		return $this->db->where( 'id', $data[ 'id' ] )->update( 'menu', $data );
	}
	
	/*
	 * 删除某一id的后台管理菜单
	 * @param int 菜单id
	 * @return bool
	 * */
	public function del_menu( $id ){
		
		return $this->db->delete( 'menu', array( 'id'=>$id ) );
	}
	/*
	 * 整理获取的菜单，写入$this->menu
	 *	@param array 混乱的菜单
	 * [
	 * 	[1]=>[
	 * 			['id']=>,
	 * 			……
	 * 			['sub']=>[]	//无下级
	 * 		]
	 * 	[2]=>[
	 * 			['id']=>,
	 * 			……
	 * 			['sub']=>[	//有下级
	 * 						[10]=>[
	 * 								['id']=>,
	 * 								……
	 * 								['sub']=>[……]
	 * 							]
	 * 					]
	 * 		]
	 * ]
	 */
	private function sort_menu( $menu ){
		
		foreach( $menu as $m ){
			if( $m[ 'parent_id' ] == 0 ){
				$sorted_menu[ $m[ 'id' ] ] = $m;
				$sorted_menu[ $m[ 'id' ] ][ 'sub' ] = array();
			}else{
				$sorted_menu[ $m['parent_id' ] ][ 'sub' ][] = $m;
			}
		}
	}
		
}
